<template>
  <div class="app-container" ref="container">
    <!-- <el-space alignment="flex-start">
      <el-scrollbar>
        <div class="tree" justify="space-between" :style="{ width: treeWidth + 'px' }" ref="treeRef">
          <Tree :treeData="treeData" :defaultProps="defaultProps" nodeKey="id" :currentNodeKey="currentKey"
            @handleNodeClick="handleNodeClick" v-loading="treeLoading" :isShowTitle="true" v-model:isExpand="isExpand"
            titleName="专题管理" />
          <el-empty v-if="treeData.length == 0" description="暂无数据" />
        </div>
      </el-scrollbar>
      <div class="queryList" :style="{ width: queryListWidth + 'px' }" ref="list">
        <p class="projectName">{{ projectName }}</p>

        <el-form :model="queryParams" ref="queryRef" :inline="true" label-width="160px">
          <el-row>
            <el-form-item label="省" prop="provinceId">
              <el-select v-model="queryParams.provinceId" placeholder="请选择省" @change="chooseProvince" clearable>
                <el-option v-for="item in provinceData" :key="item.id" :label="item.name" :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="市" prop="cityId">
              <el-select v-model="queryParams.cityId" placeholder="请选择市" @change="chooseCity" clearable>
                <el-option v-for="item in cityData" :key="item.id" :label="item.name" :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="区/县" prop="countyId">
              <el-select v-model="queryParams.countyId" placeholder="请选择区/县" clearable>
                <el-option v-for="item in areaData" :key="item.id" :label="item.name" :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-row>
          <el-row>
            <el-form-item label="专题名称" prop="name">
              <el-input v-model="queryParams.name" placeholder="请输入专题名称" clearable></el-input>
            </el-form-item>
            <el-form-item label="专题编码" prop="coding">
              <el-input v-model="queryParams.coding" placeholder="请输入专题编码" clearable></el-input>
            </el-form-item>
            <el-form-item label="专题状态" prop="status">
              <el-select v-model="queryParams.status" placeholder="请选择" clearable>
                <el-option label="进行中" value="0"></el-option>
                <el-option label="已完成" value="1"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label=" ">
              <el-button type="primary" @click="getList">查询</el-button>
              <el-button plain @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-row>
        </el-form>

        <el-divider></el-divider>
        <el-row :gutter="10" class="mb8" style="float:left">
          <el-col :span="1.5">
            <el-button type="primary" icon="Plus" @click="handleAdd" :disabled="total >= route.query.num"
              :title="total >= route.query.num ? '新建专题数量不能大于项目表单中的【专题数量】' : ''">新建</el-button>
          </el-col>
        </el-row>

        <el-table v-loading="loading" :data="dataList" :border="true" @selection-change="selectChange" stripe>
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="专题编码" align="center" prop="coding">
            <template #default="{ row }">
              <el-link type="primary" :underline="false" @click="viewOrUpdateProject(row.id)">{{ row.coding }}</el-link>
            </template>
          </el-table-column>
          <el-table-column label="专题名称" align="center" prop="name" />
          <el-table-column label="专题代码" align="center" prop="code" />
          <el-table-column label="项目名称" align="center" prop="pjName" />
          <el-table-column label="专题负责人" align="center" prop="studyDirector" />
          <el-table-column label="技术负责人" align="center" prop="technicalLeader" />
          <el-table-column label="专题状态" align="center" prop="status">
            <template #default="{ row }">
              <span v-if="row.status == '0'">进行中</span>
              <span v-else-if="row.status == '1'">已完成</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template #default="{ row }">
              <el-button type="text" @click="handleDelete(row)" v-if="row.status != '1'">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination style="margin-top: 15px" v-show="total > 0" :total="total" v-model:page="queryParams.page"
          v-model:limit="queryParams.rows" @pagination="getList" />
      </div>
    </el-space> -->
    <div class="queryList" ref="list">
        <p class="projectName">{{ projectName }}</p>

        <el-form :model="queryParams" ref="queryRef" :inline="true" label-width="160px">
          <el-row>
            <el-form-item label="省" prop="provinceId">
              <el-select v-model="queryParams.provinceId" placeholder="请选择省" @change="chooseProvince" clearable>
                <el-option v-for="item in provinceData" :key="item.id" :label="item.name" :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="市" prop="cityId">
              <el-select v-model="queryParams.cityId" placeholder="请选择市" @change="chooseCity" clearable>
                <el-option v-for="item in cityData" :key="item.id" :label="item.name" :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="区/县" prop="countyId">
              <el-select v-model="queryParams.countyId" placeholder="请选择区/县" clearable>
                <el-option v-for="item in areaData" :key="item.id" :label="item.name" :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-row>
          <el-row>
            <el-form-item label="专题名称" prop="name">
              <el-input v-model="queryParams.name" placeholder="请输入专题名称" clearable></el-input>
            </el-form-item>
            <el-form-item label="专题编码" prop="coding">
              <el-input v-model="queryParams.coding" placeholder="请输入专题编码" clearable></el-input>
            </el-form-item>
            <el-form-item label="专题状态" prop="status">
              <el-select v-model="queryParams.status" placeholder="请选择" clearable>
                <el-option label="进行中" value="0"></el-option>
                <el-option label="已完成" value="1"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label=" ">
              <el-button type="primary" @click="getList">查询</el-button>
              <el-button plain @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-row>
        </el-form>

        <el-divider></el-divider>
        <el-row :gutter="10" class="mb8" style="float:left">
          <el-col :span="1.5">
            <el-button type="primary" icon="Plus" @click="handleAdd" :disabled="total >= route.query.num"
              :title="total >= route.query.num ? '新建专题数量不能大于项目表单中的【专题数量】' : ''">新建</el-button>
          </el-col>
        </el-row>

        <el-table v-loading="loading" :data="dataList" :border="true" @selection-change="selectChange" stripe>
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="专题编码" align="center" prop="coding">
            <template #default="{ row }">
              <el-link type="primary" :underline="false" @click="viewOrUpdateProject(row.id)">{{ row.coding }}</el-link>
            </template>
          </el-table-column>
          <el-table-column label="专题名称" align="center" prop="name" />
          <el-table-column label="专题代码" align="center" prop="code" />
          <el-table-column label="项目名称" align="center" prop="pjName" />
          <el-table-column label="专题负责人" align="center" prop="studyDirector" />
          <el-table-column label="技术负责人" align="center" prop="technicalLeader" />
          <el-table-column label="专题状态" align="center" prop="status">
            <template #default="{ row }">
              <span v-if="row.status == '0'">进行中</span>
              <span v-else-if="row.status == '1'">已完成</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template #default="{ row }">
              <el-button type="text" @click="handleDelete(row)" v-if="row.status != '1'">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination style="margin-top: 15px" v-show="total > 0" :total="total" v-model:page="queryParams.page"
          v-model:limit="queryParams.rows" @pagination="getList" />
      </div>
    <el-drawer v-model="subjectDrawer" size="45%" :show-close="false" @open="openSubject" @close="closeSubject">
      <template #title>
        <h2><svg-icon icon-class="list"></svg-icon><span style="padding-left: 15px">专题管理</span></h2>
        <template v-if="!subjectIsEdit">
          <el-button plain @click="closeSubject">取消</el-button>
          <el-button type="primary" @click="confirmClick" v-if="!subjectIsEdit">保存</el-button>
        </template>
        <template v-else>
          <el-button plain @click="closeSubject">关闭</el-button>
        </template>
      </template>
      <template #default>
        <div>
          <el-form :model="subjectForm" ref="subjectRef" :rules="subjectRules" :inline="true" label-width="110px"
            :disabled="subjectIsEdit">
            <el-row justify="space-between">
              <el-form-item label="专题ID" prop="coding">
                <el-input v-model="subjectForm.coding" placeholder="请输入专题ID" clearable disabled></el-input>
              </el-form-item>
              <el-form-item label="专题名称" prop="name">
                <el-input v-model="subjectForm.name" placeholder="请输入专题名称" clearable></el-input>
              </el-form-item>
            </el-row>
            <el-row justify="space-between">
              <el-form-item label="专题代码" prop="code">
                <el-input v-model="subjectForm.code" placeholder="请输入专题代码" clearable disabled></el-input>
              </el-form-item>
              <el-form-item label="项目名称" prop="pjName">
                <el-input v-model="subjectForm.pjName" placeholder="请输入项目名称" clearable disabled></el-input>
              </el-form-item>
            </el-row>
            <el-row justify="space-between">
              <el-form-item label="项目代码" prop="pjCode">
                <el-input v-model="subjectForm.pjCode" placeholder="请输入项目代码" clearable disabled></el-input>
              </el-form-item>
              <el-form-item label="技术负责人" prop="technicalLeader">
                <el-input v-model="subjectForm.technicalLeader" placeholder="请输入技术负责人" clearable readonly
                  @click="openSelectUser('technicalLeader')"></el-input>
              </el-form-item>
            </el-row>
            <el-row justify="space-between">
              <el-form-item label="专题负责人" prop="studyDirector">
                <el-input v-model="subjectForm.studyDirector" placeholder="请输入专题负责人" clearable readonly
                  @click="openSelectUser('studyDirector')"></el-input>
              </el-form-item>
              <el-form-item label="承担单位" prop="ghii">
                <el-input v-model="subjectForm.ghii" placeholder="请输入承担单位" clearable></el-input>
              </el-form-item>
            </el-row>
            <el-row justify="space-between">
              <el-form-item label="联系方式" prop="phone">
                <el-input v-model="subjectForm.phone" placeholder="请输入联系方式" clearable></el-input>
              </el-form-item>
              <el-form-item label="创建单位" prop="founderPany">
                <el-input v-model="subjectForm.founderPany" placeholder="请输入创建单位" clearable disabled></el-input>
              </el-form-item>
            </el-row>
            <el-row justify="space-between">
              <el-form-item label="创建人" prop="founder">
                <el-input v-model="subjectForm.founder" placeholder="请输入创建人" clearable disabled></el-input>
              </el-form-item>
              <el-form-item label="数据质检员" prop="dataQc">
                <el-input v-model="subjectForm.dataQc" placeholder="请输入数据质检员" clearable readonly
                  @click="openSelectUser('dataQc')"></el-input>
              </el-form-item>
            </el-row>
            <el-row justify="space-between">
              <el-form-item label="数据入库员" prop="dataIqa">
                <el-input v-model="subjectForm.dataIqa" placeholder="请输入数据入库员" clearable readonly
                  @click="openSelectUser('dataIqa')"></el-input>
              </el-form-item>
              <el-form-item label="数据采集员" prop="dataEditor">
                <el-input v-model="subjectForm.dataEditor" placeholder="请输入数据采集员" clearable
                  @click="openSelectUser('dataEditor')"></el-input>
              </el-form-item>
            </el-row>
            <el-row justify="space-between">
              <el-form-item label="专题简介" prop="briefIntro" style="width:100%">
                <el-input v-model="subjectForm.briefIntro" placeholder="请输入专题简介" :autosize="{ minRows: 5 }"
                  type="textarea" clearable show-word-limit maxlength="500"></el-input>
              </el-form-item>
            </el-row>
          </el-form>
        </div>
      </template>
    </el-drawer>

    <el-dialog v-model="projectDialog" :title="projectForm.name" width="45%" @close="closeProject">
      <el-form :model="projectForm" ref="projectRef" label-width="140px" disabled>
        <el-form-item label="项目编码：" prop="number">{{ projectForm.number }}</el-form-item>
        <el-form-item label="省、市、区（县）：" prop="area">{{ projectForm.area }}</el-form-item>
        <el-row>
          <el-col :span="12">
            <el-form-item label="项目负责人：" prop="leader">{{ projectForm.leader }}</el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="项目创建人：" prop="founder">{{ projectForm.founder }}</el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="项目类型：" prop="type">{{ projectForm.type }}</el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="项目来源：" prop="source">{{ projectForm.source }}</el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="项目状态：" prop="status">
          <span v-if="projectForm.status == '0'">进行中</span>
          <span v-else-if="projectForm.status == '1'">已完成</span>
        </el-form-item>
        <el-form-item label="项目简介：" prop="briefIntro" style="width:100%">{{ projectForm.briefIntro }}</el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button plain @click="projectDialog = false">取消</el-button>
          <el-button type="primary" @click="updateProject(projectForm.id)">
            <span v-if="projectForm.status == '0'">修改</span>
            <span v-else-if="projectForm.status == '1'">查看</span>
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 人员选择对话框 -->
    <select-user ref="selectRef" :multi="2" v-model:show="openSelect" @getSelectList="getSelectList" />
  </div>
</template>
<script setup name="subject">
import { getProvince, getChildArea } from "@/api/system/division"
import { save, getAll, deleteList, getById, update, add } from '@/api/projectManage/subject'
import { getById as getProject, getTreeList } from '@/api/projectManage/project'
import SelectUser from '@/components/SelectUser/index'
import Tree from '@/components/Tree'
import useTreeSpace from '@/hooks/useTreeSpace'

const queryData = reactive({
  queryParams: {
    page: 1,
    rows: 10
  },
  provinceData: [],
  cityData: [],
  areaData: [],
  total: 0
})
const { queryParams, provinceData, cityData, areaData, total } = toRefs(queryData)
const tableData = reactive({
  loading: false,
  dataList: []
})
const { loading, dataList } = toRefs(tableData)
const initForm = () => ({})
const subjectData = reactive({
  subjectDrawer: false,
  subjectForm: {},
  subjectIsEdit: false
})
const subjectRules = reactive({
  coding: [{ required: true, message: '请输入专题ID', trigger: 'bulr' }],
  name: [{ required: true, message: '请输入专题名称', trigger: 'bulr' }],
  code: [{ required: true, message: '请输入专题代码', trigger: 'bulr' }],
  pjName: [{ required: true, message: '请输入项目名称', trigger: 'bulr' }],
  pjCode: [{ required: true, message: '请输入项目代码', trigger: 'bulr' }],
  technicalLeader: [{ required: true, message: '请选择技术负责人', trigger: 'change' }],
  studyDirector: [{ required: true, message: '请选择专题负责人', trigger: 'change' }],
  ghii: [{ required: true, message: '请输入承担单位', trigger: 'bulr' }],
  phone: [{ required: true, message: '请输入联系方式', trigger: 'bulr' }],
  founderPany: [{ required: true, message: '请输入创建单位', trigger: 'bulr' }],
  founder: [{ required: true, message: '请输入创建人', trigger: 'bulr' }],
  dataQc: [{ required: true, message: '请选择数据质检员', trigger: 'change' }],
  dataIqa: [{ required: true, message: '请选择数据入库员', trigger: 'change' }],
  dataEditor: [{ required: true, message: '请选择数据采集员', trigger: 'change' }],
  briefIntro: [{ required: true, message: '请输入专题简介', trigger: 'bulr' }]
})
const { subjectDrawer, subjectForm, subjectIsEdit } = toRefs(subjectData)
const projectData = reactive({
  projectDialog: false,
  projectForm: {}
})
const { projectDialog, projectForm } = toRefs(projectData)

const { proxy } = getCurrentInstance()
const router = useRouter()
const route = useRoute()

// 选择人员弹窗
const openSelect = ref(false)
let selectPerson = ''
const openSelectUser = (type) => {
  openSelect.value = true
  selectPerson = type
}
const getSelectList = (arr) => {
  let personName = arr.map(item => item.realName).join(',')
  subjectForm.value[selectPerson] = personName
  subjectForm.value[selectPerson + 'Id'] = arr.map(item => item.orgUser.userId).join(',')
}

const currentKey = ref('')
onMounted(() => {
  getProvinceData()
  getList()
})
const isExpand = ref(true)
const treeWidth = computed(() => isExpand.value ? 200 : 20)
const { container, treeRef, queryListWidth } = useTreeSpace(treeWidth.value)
const treeData = ref([])
const treeLoading = ref(false)
const defaultProps = {
  children: 'list',
  label: 'name',
}
const getTreeData = () => {
  treeLoading.value = true
  getTreeList().then(res => {
    treeData.value = res.data
    treeLoading.value = false
    projectName.value = treeData.value.find(item => item.id == route.query.id).name
    currentKey.value = route.query.id
  })
}
const projectName = ref('')
watch(dataList, () => {
  getTreeData()
}, { deep: true })
// 树形结构点击事件
const curSubjectId = ref('')
const handleNodeClick = (data, node) => {
  if (node.level === 1) {
    curSubjectId.value = node.parent.data.id
    projectDialog.value = true
    getProjectDetail(data.id)
  } else if (node.level === 2) {
    viewOrUpdateProject(data.id)
  }
  currentKey.value = route.query.id
  // console.log(currentKey)
  // setCurrentKey
}
// 查询项目详情
const getProjectDetail = (id) => {
  getProject(id).then(res => {
    projectForm.value = res.data
    // projectForm.value.area = res.data.province + '-' + res.data.city + '-' + res.data.county
    projectForm.value.area = res.data.province
    if(res.data.city) {
      projectForm.value.area = res.data.province + '-' + res.data.city
      if(res.data.county){
        projectForm.value.area = res.data.province + '-' + res.data.city + '-' + res.data.county
      }
    }
  })
}
// 省市县
const getProvinceData = () => {
  getProvince().then(res => {
    if (res.code == 200) {
      provinceData.value = res.data
    }
  })
}
const chooseProvince = (value) => {
  queryParams.value.cityId = null
  queryParams.value.countyId = null
  cityData.value = []
  areaData.value = []
  getChildArea(value).then(response => {
    cityData.value = response.data
  })
}
const chooseCity = (value) => {
  queryParams.value.countyId = null
  areaData.value = []
  getChildArea(value).then(response => {
    areaData.value = response.data
  })
}

// 查询
const getList = () => {
  loading.value = true
  getAll({ ...queryParams.value, pmId: route.query.id }).then(res => {
    dataList.value = res.data.rows
    total.value = res.data.total
    loading.value = false
  })
}
// 重置
const resetQuery = () => {
  queryParams.value.page = 1
  proxy.resetForm('queryRef')
  getList()
}
// 新建
const handleAdd = () => {
  subjectDrawer.value = true
  subjectForm.value.founder = localStorage.getItem('userName')
  subjectForm.value.founderPany = localStorage.getItem('orgName')
  add(route.query.id).then(res => {
    subjectForm.value.coding = res.data.coding
    subjectForm.value.code = res.data.code
    subjectForm.value.pjName = res.data.project.name
    subjectForm.value.pjCode = res.data.project.code
  })
}

// 删除
const handleDelete = (row) => {
  proxy.$modal.confirm('专题下所有数据将被删除，是否确定删除？').then(() => {
    return deleteList(row.id)
  }).then(() => {
    proxy.$modal.msgSuccess('删除成功！')
    getList()
  })
}

// 多选
const ids = ref([])
const selectChange = (selection) => {
  ids.value = selection.map(item => item.id)
}
// 查看专题
const viewOrUpdateProject = (id, type) => {
  subjectDrawer.value = true
  getById(id).then(res => {
    subjectForm.value = res.data
    if (subjectForm.value?.status == '1') {
      subjectIsEdit.value = true
    }
  })
}

// 保存
const confirmClick = () => {
  proxy.$refs['subjectRef'].validate((valid, fields) => {
    if (valid) {
      let data = { ...subjectForm.value, pmId: route.query.id }
      if (subjectForm.value.id) {
        update(data).then(res => {
          if (res.code == 200) {
            proxy.$modal.msgSuccess('修改成功！')
            subjectDrawer.value = false
            getList()
          }
        })
      } else {
        save(data).then(res => {
          if (res.code == 200) {
            proxy.$modal.msgSuccess('保存成功！')
            subjectDrawer.value = false
            getList()
          }
        })
      }
    } else {
      proxy.$refs['subjectRef'].scrollToField(Object.keys(fields)[0])
    }
  })
}
const openSubject = () => {
  nextTick(() => {
    proxy.$refs['subjectRef'].clearValidate()
  })
}
// 关闭专题
const closeSubject = () => {
  proxy.resetAllForm(subjectForm.value, initForm())
  subjectIsEdit.value = false
}
const closeProject = () => {
  projectDialog.value = false
}
// 项目修改
const updateProject = (proId) => {
  closeProject()
  router.push({ name: 'project', params: { proId } })
}
watch(() => route.params.subId, (newVal) => {
  if (newVal) {
    // currentKey.value = newVal
    viewOrUpdateProject(newVal)
  }
}, { immediate: true })
</script>
<style scoped lang="scss">
.app-container {
  height: 100%;

  .el-space {
    height: 100%;
    width: 100%;

    :deep(.el-space__item) {
      height: 100%;
    }

    .tree,
    .queryList {
      display: inline-block;
      height: 100%;
    }

    .projectName {
      text-align: center;
      background: #e5ebf7;
      padding: 10px 0;
      font-weight: bold;
    }
  }
  .queryList {
      display: inline-block;
      height: 100%;
    }

    .projectName {
      text-align: center;
      background: #e5ebf7;
      padding: 10px 0;
      font-weight: bold;
    }
}
</style>